var drawing = document.getElementById("drawing");

function contextTest() {
    //确定浏览器支持<canvas>元素
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        context.strokeStyle = "red";
        context.fillStyle = "#0000ff";
    }
}


function drawRect() {
    //确定浏览器支持<canvas>元素
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        /*
        * 根据Mozilla 的文档
        * http://developer.mozilla.org/en/docs/Canvas_tutorial:Basic_usage
        */
        //绘制红色矩形
        context.fillStyle = "#ff0000";
        context.fillRect(10, 10, 50, 50);
        //绘制半透明的蓝色矩形
        context.fillStyle = "rgba(0,0,255,0.5)";
        context.fillRect(30, 30, 50, 50);
    }
}

function drawStrokeRect() {
    //确定浏览器支持<canvas>元素
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        /*
        * 根据Mozilla 的文档
        * http://developer.mozilla.org/en/docs/Canvas_tutorial:Basic_usage
        */
        //绘制红色描边矩形
        context.strokeStyle = "#ff0000";
        context.strokeRect(10, 10, 50, 50);
        //绘制半透明的蓝色描边矩形
        context.strokeStyle = "rgba(0,0,255,0.5)";
        context.strokeRect(30, 30, 50, 50);
    }
}

function clearRect() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        //绘制红色矩形
        context.fillStyle = "#ff0000";
        context.fillRect(10, 10, 50, 50);
        //绘制半透明的蓝色矩形
        context.fillStyle = "rgba(0,0,255,0.5)";
        context.fillRect(30, 30, 50, 50);
        //在两个矩形重叠的地方清除一个小矩形
        context.clearRect(40, 40, 10, 10);
    }
}

function drawClock() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        //开始路径
        context.beginPath();
        //绘制外圆 。半径是99 像素;圆心位于点(100,100);2 * Math.PI表示整个圆
        context.arc(100, 100, 99, 0, 2 * Math.PI, false);
        //绘制内圆
        context.moveTo(194, 100);
        context.arc(100, 100, 94, 0, 2 * Math.PI, false);
        //绘制分针
        context.moveTo(100, 100);
        context.lineTo(100, 15);
        //绘制时针
        context.moveTo(100, 100);
        context.lineTo(35, 100);
        //描边路径
        context.stroke();

        if (context.isPointInPath(100, 100)) {
            console.log("Point (100, 100) is in the path.");
        }
        //----------------------------------------------------
        //绘制文本
        context.font = "bold 14px Arial";
        context.textAlign = "center";
        context.textBaseline = "middle";
        context.fillText("12", 100, 20);
        //起点对齐
        context.fillStyle = "#ff0000";
        context.textAlign = "start";
        context.fillText("12", 100, 40);
        //终点对齐
        context.fillStyle = "rgba(0,0,255,0.5)";
        context.textAlign = "end";
        context.fillText("12", 100, 60);
    }
}

function drawText() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        var fontSize = 100;
        context.font = fontSize + "px Arial";
        while (context.measureText("Hello world!").width > 100) {
            fontSize--;
            context.font = fontSize + "px Arial";
        }
        context.fillText("Hello world!", 10, 20);
        context.fillText("Font size is " + fontSize + "px", 10, 50);
    }
}

function drawClock2() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        //开始路径
        context.beginPath();
        //绘制外圆
        context.arc(100, 100, 99, 0, 2 * Math.PI, false);
        //绘制内圆
        context.moveTo(194, 100);
        context.arc(100, 100, 94, 0, 2 * Math.PI, false);
        //变换原点
        context.translate(100, 100);
        //绘制分针
        context.moveTo(0, 0);
        context.lineTo(0, -85);
        //绘制时针
        context.moveTo(0, 0);
        context.lineTo(-65, 0);
        //描边路径
        context.stroke();
    }
}

function saveAndrestoreTest() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        context.fillStyle = "#ff0000";
        context.save();
        context.fillStyle = "#00ff00";
        context.translate(100, 100);
        context.save();
        context.fillStyle = "#0000ff";
        context.fillRect(0, 0, 100, 200); //从点(100,100)开始绘制蓝色矩形
        context.restore();
        context.fillRect(10, 10, 100, 200); //从点(110,110)开始绘制绿色矩形
        context.restore();
        context.fillRect(0, 0, 100, 200); //从点(0,0)开始绘制红色矩形
    }
}

function drawImage() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        var image = document.images[0];
        context.drawImage(image, 10, 10);
        context.drawImage(image, 50, 10, 20, 30);
        context.drawImage(image, 0, 10, 50, 50, 0, 100, 40, 60);
    }
}

function drawShadow() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        //设置阴影
        context.shadowOffsetX = 5;
        context.shadowOffsetY = 5;
        context.shadowBlur = 4;
        context.shadowColor = "rgba(0, 0, 0, 0.5)";
        //绘制红色矩形
        context.fillStyle = "#ff0000";
        context.fillRect(10, 10, 50, 50);
        //绘制蓝色矩形
        context.fillStyle = "rgba(0,0,255,1)";
        context.fillRect(30, 30, 50, 50);
    }
}

function drawGradient() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        var gradient = context.createLinearGradient(30, 30, 70, 70);
        gradient.addColorStop(0, "white");
        gradient.addColorStop(1, "black");
        //绘制红色矩形
        context.fillStyle = "#ff0000";
        context.fillRect(10, 10, 50, 50);
        //绘制渐变矩形
        context.fillStyle = gradient;
        context.fillRect(30, 30, 50, 50);
    }
}

function createRectLinearGradient(context, x, y, width, height) {
    return context.createLinearGradient(x, y, x + width, y + height);
}

function drawGradient2() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        var gradient = createRectLinearGradient(context, 30, 30, 50, 50);
        gradient.addColorStop(0, "white");
        gradient.addColorStop(1, "black");
        //绘制渐变矩形
        context.fillStyle = gradient;
        context.fillRect(30, 30, 50, 50);
    }
}

function drawRadialGradient() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        var gradient = context.createRadialGradient(55, 55, 10, 55, 55, 30);
        gradient.addColorStop(0, "white");
        gradient.addColorStop(1, "black");
        //绘制红色矩形
        context.fillStyle = "#ff0000";
        context.fillRect(10, 10, 50, 50);
        //绘制渐变矩形
        context.fillStyle = gradient;
        context.fillRect(30, 30, 50, 50);
    }
}

function repeatTest() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        var image = document.images[0];
        context.save();
        //绘制红色矩形
        context.strokeStyle = "#ff0000";
        context.strokeRect(10, 10, 150, 150);
        context.restore();
        //绘制矩形
        context.fillStyle = context.createPattern(image, "repeat");
        context.fillRect(10, 10, 150, 150);
    }
}

function ImageTest() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d"),
            image = document.images[0],
            imageData, data,
            i, len, average,
            red, green, blue, alpha;
        //绘制原始图像
        context.drawImage(image, 0, 0);
        //取得图像数据
        imageData = context.getImageData(0, 0, image.width, image.height);
        data = imageData.data;
        console.log(data.length);
        for (i = 0, len = data.length; i < len; i += 4) {
            red = data[i];
            green = data[i + 1];
            blue = data[i + 2];
            alpha = data[i + 3];
            //求得rgb 平均值
            average = Math.floor((red + green + blue) / 3);
            //设置颜色值，透明度不变
            data[i] = average;
            data[i + 1] = average;
            data[i + 2] = average;
        }
        //回写图像数据并显示结果
        imageData.data = data;
        context.putImageData(imageData, 0, 0);
    }
}

//后绘制蓝色矩形，但是蓝色矩形在红色矩形的下面
function globalCompositeOperationTest() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        //绘制红色矩形
        context.fillStyle = "#ff0000";
        context.fillRect(10, 10, 50, 50);
        //设置合成操作
        context.globalCompositeOperation = "destination-over";
        //绘制蓝色矩形
        context.fillStyle = "rgba(0,0,255,1)";
        context.fillRect(30, 30, 50, 50);
    }
}


//半透明蓝色矩形
function globalAlphaTest() {
    if (drawing.getContext) {
        var context = drawing.getContext("2d");
        //绘制红色矩形
        context.fillStyle = "#ff0000";
        context.fillRect(10, 10, 50, 50);
        //修改全局透明度
        context.globalAlpha = 0.5;
        //绘制蓝色矩形
        context.fillStyle = "rgba(0,0,255,1)";
        context.fillRect(30, 30, 50, 50);
        //重置全局透明度
        context.globalAlpha = 0;
    }
}

//WebGL----------------------------------------------------------
function DataViewTest() {
    var buffer = new ArrayBuffer(20);
    var bytes = buffer.byteLength;
    console.log(bytes);
    //基于整个缓冲器创建一个新视图
    var view = new DataView(buffer);
    //创建一个开始于字节9 的新视图
    var view = new DataView(buffer, 9);
    //创建一个从字节9 开始到字节18 的新视图
    var view = new DataView(buffer, 9, 10);
    console.log(view.byteOffset);
    console.log(view.byteLength);
}

function DataViewTest2() {
    var buffer = new ArrayBuffer(20),
        view = new DataView(buffer),
        value;
    view.setUint16(0, 25);
    view.setUint16(2, 50); //不能从字节1 开始，因为16 位整数要用2B
    value = view.getUint16(0);
    console.log("view.getInt16(0):" + value);
    console.log("view.getInt8(0):" + view.getInt8(0));
    console.log("view.getInt8(1):" + view.getInt8(1));
    console.log("view.getInt16(2):" + view.getInt16(2));
}

//类型化视图
function arrayTest() {
//  Int8Array：表示8 位二补整数。
//  Uint8Array：表示8 位无符号整数。
//  Int16Array：表示16 位二补整数。
//  Uint16Array：表示16 位无符号整数。
//  Int32Array：表示32 位二补整数。
//  Uint32Array：表示32 位无符号整数。
//  Float32Array：表示32 位IEEE 浮点值。
//  Float64Array：表示64 位IEEE 浮点值。
    var buffer = new ArrayBuffer(50);
    //创建一个新数组，使用整个缓冲器
    var int8s = new Int8Array(buffer);
    //只使用从字节8 开始的缓冲器
    var int16s = new Int16Array(buffer, 8);
    //只使用从字节8 到字节17 的缓冲器
    var uint16s = new Uint16Array(buffer, 8, 10);

    //使用缓冲器的一部分保存8位整数，另一部分保存16位整数
    var int8s = new Int8Array(buffer, 0, 10);
    var uint16s = new Uint16Array(buffer, 10, 10);

    //需要10 个元素空间
    var int8s = new Int8Array(buffer, 0, 10 * Int8Array.BYTES_PER_ELEMENT);
    //需要5 个元素空间
    var uint16s = new Uint16Array(buffer, int8s.byteOffset + int8s.byteLength,
        5 * Uint16Array.BYTES_PER_ELEMENT);

    //创建一个数组保存10 个8 位整数（10 字节）
    var int8s = new Int8Array(10);
    //创建一个数组保存10 个16 位整数（20 字节）
    var int16s = new Int16Array(10);

    //创建一个数组保存5 个8 位整数（10 字节）
    var int8s = new Int8Array([10, 20, 30, 40, 50]);

    for (var i = 0, len = int8s.length; i < len; i++) {
        console.log("Value at position " + i + " is " + int8s[i]);
    }

    var uint16s = new Uint16Array(10);
    uint16s[0] = 65537;
    console.log(uint16s[0]); //1

    var uint16s = new Uint16Array(10),
        sub = uint16s.subarray(2, 5);
}

//WebGL
var gl;

function WebGLTest() {
    if (drawing.getContext) {
        try {
            gl = drawing.getContext("experimental-webgl");
        } catch (ex) {
            //什么也不做
            alert("WebGL context could not be created.");
        }
        if (gl) {
            //使用WebGL
            gl.clearColor(255, 0, 0, 1); //black
            gl.clear(gl.COLOR_BUFFER_BIT);
            gl.viewport(0, 0, drawing.width, drawing.height);
            //着色器-------------------------------------------------------
            var vertexGlsl = document.getElementById("vertexShader").text,
                fragmentGlsl = document.getElementById("fragmentShader").text;

            console.log(vertexGlsl);
            console.log(fragmentGlsl);
            var vertexShader = gl.createShader(gl.VERTEX_SHADER);
            gl.shaderSource(vertexShader, vertexGlsl);
            gl.compileShader(vertexShader);
            var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
            gl.shaderSource(fragmentShader, fragmentGlsl);
            gl.compileShader(fragmentShader);

            if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
                alert(gl.getShaderInfoLog(fragmentShader));
            }

            var program = gl.createProgram();
            gl.attachShader(program, vertexShader);
            gl.attachShader(program, fragmentShader);
            gl.linkProgram(program);
            gl.useProgram(program);
            //绘制三角形----------------------------------------------------
            var vertices = new Float32Array([0, 1, 1, -1, -1, -1]),
                buffer = gl.createBuffer(),
                vertexSetSize = 2,
                vertexSetCount = vertices.length / vertexSetSize,
                uColor, aVertexPosition;
            //把数据放到缓冲区
            gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
            gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
            //为片段着色器传入颜色值
            uColor = gl.getUniformLocation(program, "uColor");
            gl.uniform4fv(uColor, [0, 0, 0, 1]);
            //为着色器传入顶点信息
            aVertexPosition = gl.getAttribLocation(program, "aVertexPosition");
            gl.enableVertexAttribArray(aVertexPosition);
            gl.vertexAttribPointer(aVertexPosition, vertexSetSize, gl.FLOAT, false, 0, 0);
            //绘制三角形
            gl.drawArrays(gl.TRIANGLES, 0, vertexSetCount);
            // gl.drawArrays(gl.LINE_LOOP, 0, vertexSetCount);
            // gl.drawArrays(gl.LINE_SET, 0, vertexSetCount);
        } else {
            alert("WebGL context could not be created.");
        }
    }
}

//纹理
function textureTest() {
    if (drawing.getContext) {
        try {
            gl = drawing.getContext("experimental-webgl", {preserveDrawingBuffer: true});
        } catch (ex) {
            //什么也不做
            alert("WebGL context could not be created.");
        }
        if (gl) {
            //使用WebGL
            gl.clearColor(255, 0, 0, 1); //black
            gl.clear(gl.COLOR_BUFFER_BIT);
            gl.viewport(0, 0, drawing.width, drawing.height);

            var image = new Image(),
                texture;
            image.src = "../file/logo.pmg";
            image.onload = function () {
                texture = gl.createTexture();
                gl.bindTexture(gl.TEXTURE_2D, texture);
                gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
                //清除当前纹理
                gl.bindTexture(gl.TEXTURE_2D, null);
            };
            var pixels = new Uint8Array(25 * 25);
            gl.readPixels(0, 0, 25, 25, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

            //绘制三角形----------------------------------------------------
            var vertices = new Float32Array([0, 1, 1, -1, -1, -1]),
                buffer = gl.createBuffer(),
                vertexSetSize = 2,
                vertexSetCount = vertices.length / vertexSetSize,
                uColor, aVertexPosition;
            //把数据放到缓冲区
            gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
            gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
            //为片段着色器传入颜色值
            // uColor = gl.getUniformLocation(program, "uColor");
            // gl.uniform4fv(uColor, [0, 0, 0, 1]);
            //为着色器传入顶点信息
            aVertexPosition = gl.getAttribLocation(program, "aVertexPosition");
            gl.enableVertexAttribArray(aVertexPosition);
            gl.vertexAttribPointer(aVertexPosition, vertexSetSize, gl.FLOAT, false, 0, 0);
            //绘制三角形
            gl.drawArrays(gl.TRIANGLES, 0, vertexSetCount);
        } else {
            alert("WebGL context could not be created.");
        }
    }
}
